package cn.elead.chaos.sso.server.web.login.controller;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.eventbus.AsyncEventBus;

import cn.elead.chaos.core.constant.Constants;
import cn.elead.chaos.framework.util.RequestUtils;
import cn.elead.chaos.ip.Util;
import cn.elead.chaos.mybatils.web.controller.BaseController;
import cn.elead.chaos.sso.server.web.monitor.domain.SysLogininfor;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;

/**
 * 登录日志
 * 
 * @author luopeng
 *
 */
@Slf4j
public class LogController extends BaseController {

	@Autowired
	private AsyncEventBus eventBus;

	/**
	 * 登录信息
	 * @param username
	 * @param status
	 * @param message
	 * @param args
	 */
	public void recordLogininfor(final String username, final String status, final String message, final Object... args) {
		recordLogininfor("-1", username, status, message, args);
	}

	/**
	 * 登录信息
	 * @param sessionId
	 * @param username
	 * @param status
	 * @param message
	 * @param args
	 */
	public void recordLogininfor(final String sessionId, final String username, final String status, final String message, final Object... args) {

		final UserAgent userAgent = UserAgent.parseUserAgentString(RequestUtils.getRequest().getHeader("User-Agent"));
		// 请求的地址
		String ip = Util.getIpAddr(request);
		String address = Util.getCityInfo(ip);
		StringBuilder s = new StringBuilder();
		s.append(getBlock(ip));
		s.append(address);
		s.append(getBlock(username));
		s.append(getBlock(status));
		s.append(getBlock(message));
		// 打印信息到日志
		log.info(s.toString(), args);
		// 获取客户端操作系统
		String os = userAgent.getOperatingSystem().getName();
		// 获取客户端浏览器
		String browser = userAgent.getBrowser().getName();
		// 封装对象
		SysLogininfor logininfor = new SysLogininfor();
		logininfor.setSessionId(sessionId);
		logininfor.setLoginName(username);
		logininfor.setIpaddr(ip);
		logininfor.setLoginLocation(address);
		logininfor.setBrowser(browser);
		logininfor.setOs(os);
		logininfor.setMsg(message);
		// 日志状态
		if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
			logininfor.setStatus(Constants.SUCCESS);
		} else if (Constants.LOGIN_FAIL.equals(status)) {
			logininfor.setStatus(Constants.FAIL);
		}

		eventBus.post(logininfor);
	}

	public static String getBlock(Object msg) {
		if (msg == null) {
			msg = "";
		}
		return "[" + msg.toString() + "]";
	}
}